package Servlet.admin;

import Utils.DruidUtils;
import domain.SysUser;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/adminRegister")
public class RegisterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户输入的数据
        String req_amdin = request.getParameter("admin");
        String req_pwd1 = request.getParameter("pwd1");
        String req_pwd2 = request.getParameter("pwd2");
        String req_tel = request.getParameter("tel");
        String req_code = request.getParameter("code");
        boolean flag=false;

        // 获取session
        HttpSession session = request.getSession();

        // 保存用户输入的数据
        session.setAttribute("admin_register_req_user", req_amdin);
        session.setAttribute("admin_register_req_pwd1", req_pwd1);
        session.setAttribute("admin_register_req_pwd2", req_pwd2);
        session.setAttribute("admin_register_req_tel", req_tel);
        session.setAttribute("admin_register_req_code", req_code);


        // 检查用户输入的是否为空
        if (req_amdin == "" && req_pwd1 == "" && req_pwd2 == "" && req_tel == "") {
            // 把错误信息储存到域对象中
            request.setAttribute("admin_register_from_info", "表单不能为空");
//            System.out.println("都为空");
            // 跳转到register.jsp页面，让用户重新输入
            request.getRequestDispatcher("./admin/register.jsp").forward(request,response);
        } else {
            // 当用户输入数据时
            request.setAttribute("admin_register_from_info", "");
            // 数据库操作
            try {

                // 写SQL语句
                String sql_select = "select user_name as userName, pwd from sys_admin";
//                String sql_insert = "insert into test(UserName,Password,tel) values('" + req_user + "','" + req_pwd1 + "','"+req_tel+"')";
                String sql_insert = "insert into test(user_name,pwd,tel) values(?, ?, ?)";

                QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
                List<SysUser> adminList = queryRunner.query(sql_select, new BeanListHandler<>(SysUser.class));

                for (SysUser admin : adminList) {
                    if (req_amdin.equals(admin.getUserName())) {
                        // 将错误信息储存到域对象中
                        request.setAttribute("admin_register_user_info", "该用户已存在");
                        break;
                    }else {
                        request.setAttribute("admin_register_user_info", "");
                    }
                }

                // 满足条件时，添加数据；否则返回失败相关信息
//                if (ReUtil.isMatch("^(?=.*[A-Za-z]).{8,}$", req_pwd1) && req_pwd1.equals(req_pwd2) && ReUtil.isMatch("^(19|14|15|18|13)[0-9]{9}$", req_tel) && req_code.equals(session.getAttribute("code"))){
                if (SysUser.isValidPassword(req_pwd1) && SysUser.equalsPassword(req_pwd1, req_pwd2) && SysUser.isValidPhoneNumber(req_tel) && req_code.equals(session.getAttribute("code"))){
                    // 添加数据
                    queryRunner.update(sql_insert, req_amdin, req_pwd1, req_tel);
                    flag=true;

                }else {
                    // 检查表单，并将错误信息储存到域对象中
                    // 验证密码安全性
                    if (!SysUser.isValidPassword(req_pwd1)) {
                        request.setAttribute("admin_register_pwd1_info", "密码至少8位，其中有1位大写或小写字母构成");
                    }else {
                        request.setAttribute("admin_register_pwd1_info", "");
                    }

                    // 判断两个密码是否相等
                    if (!SysUser.equalsPassword(req_pwd1, req_pwd2)) {
                        request.setAttribute("admin_register_pwd2_info", "两次密码不相同");
                    }else {
                        request.setAttribute("admin_register_pwd2_info", "");
                    }

                    // 手机号码验证
                    if (!SysUser.isValidPhoneNumber(req_tel)) {
                        request.setAttribute("admin_register_tel_info", "电话号码格式不正确");
                    }else {
                        request.setAttribute("admin_register_tel_info", "");
                    }

                    // 判断验证码是否正确
                    if (!req_code.equals(session.getAttribute("code"))){
                        request.setAttribute("admin_register_code_info","验证码错误");
                    }else {
                        request.setAttribute("admin_register_code_info","");
                    }
                }

//                System.out.println("执行完毕！");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // 如果flag为true跳转到注册成功页面；若为false跳转到register.jsp页面，用户重新输入
        if (flag){
            request.getRequestDispatcher("/registerSuccess.jsp").forward(request,response);
        }else {
            request.getRequestDispatcher("/admin/register.jsp").forward(request,response);
        }
    }
}
